import os
import json
import requests
from mcp.server.fastmcp import FastMCP
from datetime import datetime


mcp = FastMCP(host='0.0.0.0', port=9876)


@mcp.tool()
async def current_time():
    """获取当前日期和时间。当用户需要处理当前、最新或实时等问题时，可首先调用本工具获取当前时间，然后再调用其他工具来解决问题
    """
    now_time = datetime.now()
    return now_time.strftime('%Y-%m-%dT%H:%M:%S')


@mcp.tool()
async def address2geolocation(address: str) -> str:
    """地理编码：根据地理位置描述（如城市名、地名等）求解其地理经纬度坐标和城市编码
    :param address: 地理位置描述（如城市名、地名等）
    :return: 地理经纬度坐标，格式为： "<经度>,<纬度>,<城市编码>"
    """
    gaode_appkey = os.environ['GAODEAPPKEY']
    url = f'https://restapi.amap.com/v3/geocode/geo?address={address}&output=JSON&key={gaode_appkey}'

    try:
        res = requests.get(url)
    except Exception as e:
        return str(e)

    if res.status_code != 200:
        return res.text

    result = json.loads(res.text)
    return result['geocodes'][0]['location'] + ',' + result['geocodes'][0]['citycode']


@mcp.tool()
async def weather_forecast(location: str) -> str:
    """天气预报： 根据地理经纬度坐标预测当地三天内天气情况
    :param location: 地理经纬度坐标，格式为： "<经度>,<纬度>"
    :return: 天气预报结果，JSON格式的字符串
    """
    caiyun_appkey = os.environ['CAIYUNAPPKEY']
    url = f'https://api.caiyunapp.com/v2.6/{caiyun_appkey}/{location}/daily?dailysteps=3'

    try:
        res = requests.get(url)
    except Exception as e:
        return str(e)

    return res.text


@mcp.tool()
async def driving(origin: str, destination: str) -> str:
    """驾车路线规划：根据起点和目的地的地理位置描述规划驾车路线
    :param origin: 起点经纬度，经度在前，纬度在后，经度和纬度用","分割，经纬度小数点后不得超过6位，例如：116.481028,39.989643
    :param destination: 目的地经纬度，经度在前，纬度在后，经度和纬度用","分割，经纬度小数点后不得超过6位，例如：116.434446,39.90816
    :return: 规划路径返回结果，JSON格式的字符串
    """
    gaode_appkey = os.environ['GAODEAPPKEY']
    url = f'https://restapi.amap.com/v5/direction/driving?origin={origin}&destination={destination}&key={gaode_appkey}'

    try:
        res = requests.get(url)
    except Exception as e:
        return str(e)

    return res.text


@mcp.tool()
async def walking(origin: str, destination: str) -> str:
    """步行路线规划：根据起点和目的地的地理位置描述规划步行路线
    :param origin: 起点经纬度，经度在前，纬度在后，经度和纬度用","分割，经纬度小数点后不得超过6位，例如：116.481028,39.989643
    :param destination: 目的地经纬度，经度在前，纬度在后，经度和纬度用","分割，经纬度小数点后不得超过6位，例如：116.434446,39.90816
    :return: 规划路径返回结果，JSON格式的字符串
    """
    gaode_appkey = os.environ['GAODEAPPKEY']
    url = f'https://restapi.amap.com/v5/direction/walking?origin={origin}&destination={destination}&key={gaode_appkey}'

    try:
        res = requests.get(url)
    except Exception as e:
        return str(e)

    return res.text


@mcp.tool()
async def bicycling(origin: str, destination: str) -> str:
    """骑行路线规划：根据起点和目的地的地理位置描述规划骑行路线
    :param origin: 起点经纬度，经度在前，纬度在后，经度和纬度用","分割，经纬度小数点后不得超过6位，例如：116.481028,39.989643
    :param destination: 目的地经纬度，经度在前，纬度在后，经度和纬度用","分割，经纬度小数点后不得超过6位，例如：116.434446,39.90816
    :return: 规划路径返回结果，JSON格式的字符串
    """
    gaode_appkey = os.environ['GAODEAPPKEY']
    url = f'https://restapi.amap.com/v5/direction/bicycling?origin={origin}&destination={destination}&key={gaode_appkey}'

    try:
        res = requests.get(url)
    except Exception as e:
        return str(e)

    return res.text


@mcp.tool()
async def transit(origin: str, destination: str, city1: str, city2: str) -> str:
    """公交路线规划：根据起点和目的地的地理位置描述规划公交出行路线
    :param origin: 起点经纬度，经度在前，纬度在后，经度和纬度用","分割，经纬度小数点后不得超过6位，例如：116.481028,39.989643
    :param destination: 目的地经纬度，经度在前，纬度在后，经度和纬度用","分割，经纬度小数点后不得超过6位，例如：116.434446,39.90816
    :param city1: 起点所在城市的城市编码（citycode）
    :param city2: 目的地所在城市的城市编码（citycode）
    :return: 规划路径返回结果，JSON格式的字符串
    """
    gaode_appkey = os.environ['GAODEAPPKEY']
    url = f'https://restapi.amap.com/v5/direction/transit/integrated?origin={origin}&destination={destination}&city1={city1}&city2={city2}&key={gaode_appkey}'

    try:
        res = requests.get(url)
    except Exception as e:
        return str(e)

    return res.text


if __name__ == '__main__':
    mcp.run(transport='streamable-http')
